<template>
  <div class="w-full h-full px-4 flex flex-col overflow-hidden" style="height: 88vh;">
    <div class="py-4 flex-shrink-0" style="height: 55px">
      <el-button type="success" :icon="Printer" @click="printAll">{{
          $t("cim.PrintSelection")
        }}</el-button>
      <!--      <el-button type="danger" :icon="Delete" @click="deleteAll">{{$t('cim.BatchDeletion')}}</el-button>-->
    </div>
    <div class="card-scroll-container flex-shrink-0" v-if="cardList.length" style="height: 200px">
      <div
          class="card-scroll-wrapper"
          ref="scrollContainer"
          @mousedown="startDrag"
          @mousemove="onDrag"
          @mouseup="stopDrag"
          @mouseleave="stopDrag"
          @scroll="updateScrollProgress"
      >
        <card-item
            v-for="(item, index) in cardList"
            :key="index"
            :index="index"
            :item="item"
            :length="cardList.length"
        />
      </div>
      <!-- 自定义滚动条 -->
      <div class="custom-scrollbar" v-if="cardList.length > 0">
        <div
            class="scrollbar-track"
            @click="scrollToPosition"
            ref="scrollbarTrack"
        >
          <div
              class="scrollbar-thumb"
              :style="{
                width: scrollbarThumbWidth + 'px',
                left: scrollbarThumbLeft + 'px'
              }"
              @mousedown="startScrollbarDrag"
          ></div>
        </div>
      </div>
    </div>
    <div class="table-list w-full flex-1 flex flex-col min-h-0 overflow-hidden">
      <el-table
          v-model="selectedRows"
          border
          id="out-table"
          :fit="true"
          :data="data.list"
          table-layout="fixed"
          header-align="center"
          class="from-box flex-1"
          style="width: 100%;"
          :header-cell-style="{
            color: '#1e293b',
            textAlign: 'center',
            fontWeight: '600',
            borderColor: '#e2e8f0',
            height: '40px',
          }"
          :cell-style="{
            textAlign: 'center',
            color: '#334155',
            borderColor: '#e2e8f0',
            background: '#fff',
            height: '60px',
          }"
          scrollbar-always-on
          :row-class-name="tableRowClassName"
          @select="handleSelectionChange"
          @select-all="handleSelectionAll"
      >
        <el-table-column
            type="selection"
            fixed="left"
            class-name="selection"
        />
        <el-table-column
            width="180"
            fixed="left"
            class-name="selection"
            :label="$t('cim.operation')"
        >
          <template #default="scope">
            <div class="flex">
              <el-button
                  link
                  type="primary"
                  size="small"
                  :icon="Refresh"
                  @click.prevent="updateImg(scope.row.id)"
              >
                {{ $t("cim.ReUpload") }}
              </el-button>
              <el-button
                  link
                  type="warning"
                  size="small"
                  :icon="Printer"
                  @click.prevent="print(scope.row.id)"
              >
                {{ $t("cim.Print") }}
              </el-button>
              <!--              <el-button-->
              <!--                link-->
              <!--                type="danger"-->
              <!--                size="small"-->
              <!--                :icon="Delete"-->
              <!--                @click.prevent="deleteRow(scope.row.id)"-->
              <!--              >-->
              <!--                {{$t('cim.delete')}}-->
              <!--              </el-button>-->
            </div>
          </template>
        </el-table-column>
        <el-table-column
            fixed="left"
            width="120"
            class-name="selection"
            prop="pictureUrl"
            :label="$t('cim.picture')"
        >
          <template v-slot="scope">
            <div class="w-full h-full flex justify-center">
              <img
                  v-if="scope.row.pictureUrl"
                  @click="previewImg(scope.row.pictureUrl)"
                  :src="scope.row.pictureUrl"
                  style="width: 80px; height: 60px"
                  class="uploaded-image"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column
            width="120"
            fixed="left"
            class-name="selection"
            prop="design"
            :label="$t('cim.FlowerColor')"
        />
        <el-table-column label="JC/Extrusion" class-name="JC_Extrusion">
          <el-table-column
              width="140"
              prop="isocoreMaterialCode"
              :label="$t('cim.sheetMaterial')"
              class-name="JC_Extrusion_box"
          />
          <el-table-column
              width="140"
              prop="isocoreSpecification"
              :label="$t('cim.plasticBoard')"
              class-name="JC_Extrusion_box"
              show-overflow-tooltip
          />
        </el-table-column>
        <el-table-column label="TH/Gluing" class-name="TH_Gluing">
          <el-table-column
              width="120"
              class-name="TH_Gluing_box"
              prop="lvtModel"
              :label="$t('cim.UpperSubstrate')"
          />
          <el-table-column
              width="120"
              class-name="TH_Gluing_box"
              prop="embossing"
              :label="$t('cim.EmbossedPattern')"
          />
          <el-table-column
              width="140"
              class-name="TH_Gluing_box"
              prop="lvtMaterialCode"
              :label="$t('cim.UpperMaterialCode')"
          />
          <el-table-column
              width="120"
              class-name="TH_Gluing_box"
              prop="lvtSpecification"
              :label="$t('cim.SpecificationSubstrate')"
          />
          <el-table-column
              width="180"
              class-name="TH_Gluing_box"
              prop="coatingIsocoreMaterialCode"
              :label="$t('cim.largePiecesMaterial')"
          />
          <el-table-column
              width="140"
              class-name="TH_Gluing_box"
              prop="coatingIsocoreSpecification"
              :label="$t('cim.sheetMaterialSpecifications')"
          />
          <el-table-column
              width="160"
              class-name="TH_Gluing_box"
              prop="coatingIsocoreProductionLine"
              :label="$t('cim.ProductionLine')"
          >
            <template v-slot="scope">
              <div class="flex items-center justify-center flex-col">
                <el-tag
                    type="primary"
                    class="mb-1"
                    v-for="item in scope.row.coatingIsocoreProductionLine"
                    :key="item"
                >{{ item }}</el-tag
                >
                <span v-if="!scope.row.coatingIsocoreProductionLine.length"
                >--</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="JKJ/Saw cutting" class-name="JKJ_Saw">
          <el-table-column
              width="180"
              class-name="JKJ_Saw_box"
              prop="sawingIsocoreMaterialCode"
              :label="$t('cim.SlottedSmallPiece')"
          />
          <el-table-column
              width="180"
              class-name="JKJ_Saw_box"
              prop="sawingIsocoreSpecification"
              :label="$t('cim.SlottedSmallSpecification')"
          />
        </el-table-column>
        <el-table-column label="PE" class-name="PE">
          <el-table-column
              width="230"
              class-name="PE_box"
              prop="underlaymentMaterialCode"
              :label="$t('cim.BottomFilmCoding')"
          />
          <el-table-column
              width="230"
              class-name="PE_box"
              prop="underlaymentIsocoreMaterialCode"
              :label="$t('cim.CodingOfSmall')"
          />
          <el-table-column
              width="230"
              class-name="PE_box"
              prop="underlaymentIsocoreSpecification"
              :label="$t('cim.BottomFilmSmallPiece')"
          />
        </el-table-column>
        <el-table-column label="DR/Pack and wrap" class-name="DR_Pack">
          <el-table-column
              width="120"
              class-name="DR_Pack_box"
              prop="finishedGoodsMaterialCode"
              :label="$t('cim.FinishedProductMaterialCode')"
          />
          <el-table-column
              width="120"
              class-name="DR_Pack_box"
              prop="cartonMaterialCode"
              :label="$t('cim.PaperMaterialCode')"
          />
          <el-table-column
              width="150"
              class-name="DR_Pack_box"
              prop="manualMaterialCode"
              :label="$t('cim.instructionMaterial')"
          />
          <el-table-column
              width="120"
              class-name="DR_Pack_box"
              prop="tagMaterialCode"
              :label="$t('cim.StickersMaterialCode')"
          />
          <el-table-column
              width="160"
              class-name="DR_Pack_box"
              prop="finishedGoodsProductionLine"
              :label="$t('cim.ProductionLine')"
          >
            <template v-slot="scope">
              <div class="flex items-center justify-center flex-col">
                <el-tag
                    class="mb-1"
                    type="primary"
                    v-for="item in scope.row.finishedGoodsProductionLine"
                    :key="item"
                >{{ item }}</el-tag
                >
                <span v-if="!scope.row.finishedGoodsProductionLine.length"
                >--</span
                >
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
      <div class="pagination-container flex-shrink-0 py-4">
        <el-pagination
            :current-page="data.page"
            :page-size="data.rows"
            :page-sizes="[5, 10, 20, 50, 100]"
            size="small"
            background
            class="custom-pagination"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
            @size-change="handleCurrentSizeChange"
            @current-change="handleCurrentPageChange"
        />
      </div>
    </div>
    <el-dialog
        v-model="dialogFormVisible"
        @close="closeDialog"
        :title="!rowId ? $t('cim.AddColorInformation') : $t('cim.ReUpload')"
        width="600px"
        style="border-radius: 8px"
    >
      <el-form :model="data.form" :rules="rules" ref="formRef">
        <el-form-item
            v-if="!rowId"
            :label="$t('cim.FlowerColor')"
            prop="name"
            label-width="80px"
        >
          <!--          <el-input v-model="data.form.name" :placeholder="$t('cim.PleaseEnter')" autocomplete="off" />-->
          <el-select
              v-model="data.form.name"
              :placeholder="$t('cim.PleaseChoose')"
              @change="nameSelected"
          >
            <el-option
                v-for="(item, index) in sleList"
                :key="index"
                :label="item.design"
                :value="item.materialCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item
            v-if="!rowId"
            :label="$t('cim.FinishedNumber')"
            prop="region"
            label-width="80px"
        >
          <el-input v-model="data.form.region" disabled autocomplete="off" />
          <!--          <el-select v-model="data.form.region" :placeholder="$t('cim.PleaseChoose')">-->
          <!--            <el-option v-for="(item,index) in sleList" :key="index" :label="item" :value="item" />-->
          <!--          </el-select>-->
        </el-form-item>
        <el-form-item
            :label="$t('cim.picture')"
            prop="imageUrl"
            label-width="80px"
        >
          <el-upload
              v-loading="loadingImg"
              class="avatar-uploader"
              :action="'/api/eletile-digital/sys-minio/upload'"
              :headers="headers"
              :show-file-list="false"
              name="file"
              :disabled="!!data.form.imageUrl"
              :on-progress="handleUploadStart"
              :on-error="handleUploadError"
              :on-success="handleAvatarSuccess"
              :data="formData"
              :before-upload="beforeAvatarUpload">
            <img
                v-if="data.form.imageUrl"
                :src="data.form.imageUrl"
                class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <span
                v-if="data.form.imageUrl"
                class="delete-tag"
                @click.stop="handleRemoveImage"
            >×</span
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">{{ $t("cim.Cancel") }}</el-button>
          <el-button type="primary" @click="confirm" :loading="loading">
            {{ $t("cim.Confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="previewVisible" width="800px" align-center>
      <div class="preview-container">
        <img :src="previewUrl" :alt="previewTitle" class="preview-image" />
      </div>
    </el-dialog>

    <el-dialog
        v-model="dialogPrintFormVisible"
        @close="closePrintDialog"
        :title="$t('cim.PrintConfiguration')"
        width="600px"
        style="border-radius: 8px"
    >
      <el-form :model="data.printForm" :rules="printRules" ref="printFormRef">
        <el-form-item
            :label="$t('cim.printer')"
            prop="printer"
            label-width="150px"
        >
          <el-select
              v-model="data.printForm.printer"
              :placeholder="$t('cim.selectPrinter')"
          >
            <el-option
                v-for="item in printerList"
                :key="item.id"
                :label="item.text"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
            :label="$t('cim.isProductionLine')"
            prop="isShowLine"
            label-width="150px"
        >
          <el-radio-group v-model="data.printForm.isShowLine">
            <el-radio :label="'1'">{{ $t("cim.yes") }}</el-radio>
            <el-radio :label="'0'">{{ $t("cim.no") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closePrintDialog">{{
              $t("cim.Cancel")
            }}</el-button>
          <el-button type="primary" @click="confirmPrint" :loading="loading">
            {{ $t("cim.Confirm") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import '/@/style/tailwind.css';
import CardItem from './cardItem.vue'
import { onMounted, onUnmounted, reactive, ref, nextTick, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus'
import { Plus, Printer, Refresh } from '@element-plus/icons-vue'

import {
  getInfo,
  getMesColorDetailSave,
  updatePictureUrl,
  getColorCard,
  getPrint,
  setPrint
} from '/@/api/platform/mes/colorInformationApi'
import {Session} from "/@/utils/storage";

const { t } = useI18n()

const data = reactive({
  form: {
    name: '',
    region: '',
    imageUrl: ''
  },
  printForm: {
    printer: '',
    isShowLine: '1'
  },
  list: [],
  page: 1,
  rows: 10,
  total: 0
})
const baseURL = ref()
const formRef = ref(null)
const sleList = ref([])
const loading = ref(false)
const action = ref()
const previewUrl = ref()
const loadingImg = ref(false)
const previewVisible = ref(false)
const selectedRows = ref()
const rowId = ref()
const printId = ref()
const cardList = ref([])
const isSingle = ref(false)

const dialogFormVisible = ref(false)
const dialogPrintFormVisible = ref(false)
const printFormRef = ref()
const printerList = ref([])

// 滚动相关
const scrollContainer = ref(null)
const isDragging = ref(false)
const startX = ref(0)
const scrollLeft = ref(0)
const autoScrollInterval = ref(null)
const autoScrollDirection = ref(1) // 1 for right, -1 for left

// 滚动条相关
const scrollbarTrack = ref(null)
const scrollbarThumbWidth = ref(0)
const scrollbarThumbLeft = ref(0)
const isScrollbarDragging = ref(false)
const scrollbarStartX = ref(0)
const scrollbarThumbStartLeft = ref(0)

const rules = {
  name: [
    { required: true, message: t('cim.EnterColorScheme'), trigger: 'blur' }
  ],
  region: [
    {
      required: true,
      message: t('cim.SelectFinishedProduc'),
      trigger: 'change'
    }
  ],
  imageUrl: [
    { required: true, message: t('cim.UploadPictures'), trigger: 'change' }
  ]
}
const printRules = {
  printer: [
    { required: true, message: t('cim.selectPrinter'), trigger: 'blur' }
  ],
  isShowLine: [
    {
      required: true,
      message: t('cim.confirmProductionLine'),
      trigger: 'change'
    }
  ]
}

const nameSelected = () => {
  data.form.region = data.form.name
}
// 获取打印机
const getPrintList = async () => {
  try {
    const res = await getPrint()
    printerList.value = res
  } catch (e) {
    console.log(e)
  }
}
const openPrintDialog = () => {
  if (printFormRef.value) {
    printFormRef.value.resetFields()
  }
  data.printForm = {
    printer: '',
    isShowLine: '1'
  }
  dialogPrintFormVisible.value = true
}
const closePrintDialog = () => {
  if (printFormRef.value) {
    printFormRef.value.resetFields()
  }
  data.printForm = {
    printer: '',
    isShowLine: '1'
  }
  printId.value = ''
  dialogPrintFormVisible.value = false
}
const confirmPrint = async () => {
  printFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        await setPrint(
          isSingle.value
            ? [printId.value]
            : selectedRows.value?.map((item) => item.id),
          data.printForm.isShowLine,
          data.printForm.printer
        )
        ElMessage({
          message: t('cim.OperationSuccessful'),
          type: 'success',
          plain: true
        })
      } catch (e) {
        console.log(e)
        ElMessage({
          message: e.message,
          type: 'error',
          plain: true
        })
      }
      dialogPrintFormVisible.value = false
      loading.value = false
      isSingle.value = false
    } else {
      dialogPrintFormVisible.value = true
      loading.value = false
    }
  })
}
// 新增
const add = () => {
  openDialog()
}

const headers = computed(() => {
  return {
    Authorization: 'Bearer ' + Session.getToken(),
    'TENANT-ID': Session.getTenant(),
  };
});
// 弹窗相关
const openDialog = () => {

  // 重置表单字段，清除校验信息
  if (formRef.value) {
    formRef.value.resetFields()
  }
  data.form = {
    name: '',
    region: '',
    imageUrl: ''
  }
  dialogFormVisible.value = true
}
const closeDialog = () => {
  // 重置表单字段，清除校验信息
  if (formRef.value) {
    formRef.value.resetFields()
  }
  data.form = {
    name: '',
    region: '',
    imageUrl: ''
  }
  rowId.value = ''
  dialogFormVisible.value = false
}
const confirm = async () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        if (!rowId.value) {
          let design = ''
          sleList.value.forEach((item) => {
            if (data.form.name === item.materialCode) {
              design = item.design
            }
          })

          const res = await getMesColorDetailSave({
            design: design,
            finishedGoodsMaterialCode: data.form.region,
            pictureUrl: data.form.imageUrl
          })
          if (res.statusCode === 300) {
            ElMessage({
              message: res.message,
              type: 'error',
              plain: true
            })
          } else {
            dialogFormVisible.value = false
            loading.value = false
            ElMessage({
              message: t('cim.AddedSuccessfully'),
              type: 'success',
              plain: true
            })
            getMesColorDetail()
          }
        } else {
          await updatePictureUrl({
            id: rowId.value,
            pictureUrl: data.form.imageUrl
          })
          dialogFormVisible.value = false
          loading.value = false
          ElMessage({
            message: t('cim.updateSuccessful'),
            type: 'success',
            plain: true
          })
          getMesColorDetail()
        }
      } catch (e) {
        console.log(e)
        ElMessage({
          message: e.message,
          type: 'error',
          plain: true
        })
        loading.value = false
      }
    } else {
      dialogFormVisible.value = true
    }
  })
}
const tableRowClassName = ({ row }) => {
  return row.finishedGoodsProductionLine.length ||
  row.coatingIsocoreProductionLine.length
    ? 'bgColor'
    : ''
}
// 勾选
const handleSelectionChange = (selected) => {
  selectedRows.value = selected // 更新选中的行
}
const handleSelectionAll = (selected) => {
  selectedRows.value = selected // 更新选中的行
}
const previewImg = (url) => {
  previewUrl.value = url
  previewVisible.value = true
}
// 获取列表
const getMesColorDetail = async () => {
  try {
    const res = await getInfo({
      current: data.page,
      size: data.rows
    })
    data.list = res.data.records.map((item) => {
      return {
        ...item,
        coatingIsocoreProductionLine: item.coatingIsocoreProductionLine
          ? item.coatingIsocoreProductionLine
            .split(',')
            .map((line) => line.trim())
          : [],
        finishedGoodsProductionLine: item.finishedGoodsProductionLine
          ? item.finishedGoodsProductionLine
            .split(',')
            .map((line) => line.trim())
          : []
      }
    })
    data.total = res.data.total
  } catch (e) {
    console.log(e)
  }
}
// 分页
const handleCurrentSizeChange = (val) => {
  data.rows = val
  getMesColorDetail()
}
const handleCurrentPageChange = (val) => {
  data.page = val
  getMesColorDetail()
}
// 单个打印
const print = (id) => {
  printId.value = id
  isSingle.value = true
  openPrintDialog()
}

// 打印所有
const printAll = async () => {
  if (!selectedRows.value?.length) {
    return ElMessage({ type: 'error', message: t('cim.selectTheData') })
  }
  openPrintDialog()
}
const formData = reactive(new FormData())
// 图片上传相关钩子
const beforeAvatarUpload = (rawFile) => {


  // 添加必要的字段
  formData.append('id', rawFile.uid); // 根据你的需求设置 ID
  formData.append('type', 'colorInformation'); // 根据你的需求设置类型
  formData.append('file', rawFile); // 直接添加文件

  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    return true
  } else {
    ElMessage({
      type: 'error',
      message: '上传的文件类型必须是PNG|JPG|GIF'
    })
    return false
  }
}
const handleUploadStart = () => {
  loadingImg.value = true
}
const handleUploadError = () => {
  loadingImg.value = false
}
const handleAvatarSuccess = (response) => {
  // 处理返回值，例如更新图片 URL
  loadingImg.value = false
  if (response) {
    // data.form.imageUrl = response.data // 根据实际返回值结构修改
    // 将原始 URL 替换为新的 URL
    let url = ''
    const environment = process.env.NODE_ENV
    if (environment === 'production') {
      url = 'http://10.133.100.100:9000/platform'
    } else {
      url = 'http://10.1.7.105:9001/platform'
    }
    data.form.imageUrl = url + response


  }
}
const handleRemoveImage = () => {
  data.form.imageUrl = ''
}

// 重新上传图片
const updateImg = (id) => {
  rowId.value = id
  openDialog()
}
// 获取正在生产的产线信息
const getCardList = async () => {
  try {
    const res = await getColorCard()
    cardList.value = res
  } catch (e) {
    console.log(e)
  }
}

// 滚动相关方法
const startDrag = (e) => {
  isDragging.value = true
  startX.value = e.pageX - scrollContainer.value.offsetLeft
  scrollLeft.value = scrollContainer.value.scrollLeft
  scrollContainer.value.style.cursor = 'grabbing'
  scrollContainer.value.style.userSelect = 'none'

  // 停止自动滚动
  stopAutoScroll()
}

const onDrag = (e) => {
  if (!isDragging.value) return
  e.preventDefault()
  const x = e.pageX - scrollContainer.value.offsetLeft
  const walk = (x - startX.value) * 2
  scrollContainer.value.scrollLeft = scrollLeft.value - walk
}

const stopDrag = () => {
  isDragging.value = false
  if (scrollContainer.value) {
    scrollContainer.value.style.cursor = 'grab'
    scrollContainer.value.style.userSelect = 'auto'
  }

  // 重新开始自动滚动
  startAutoScroll()
}

const startAutoScroll = () => {
  if (autoScrollInterval.value) return

  autoScrollInterval.value = setInterval(() => {
    if (!scrollContainer.value || isDragging.value) return

    const container = scrollContainer.value
    const maxScroll = container.scrollWidth - container.clientWidth

    if (container.scrollLeft >= maxScroll) {
      autoScrollDirection.value = -1
    } else if (container.scrollLeft <= 0) {
      autoScrollDirection.value = 1
    }

    container.scrollLeft += autoScrollDirection.value * 2
  }, 50)
}

const stopAutoScroll = () => {
  if (autoScrollInterval.value) {
    clearInterval(autoScrollInterval.value)
    autoScrollInterval.value = null
  }
}

// 滚动条相关方法
const updateScrollProgress = () => {
  if (!scrollContainer.value) return

  const container = scrollContainer.value
  const maxScroll = container.scrollWidth - container.clientWidth
  const currentScroll = container.scrollLeft

  if (maxScroll > 0) {
    // 计算滚动条滑块宽度和位置
    const trackWidth = scrollbarTrack.value?.clientWidth || 0
    const thumbWidth = Math.max(30, (container.clientWidth / container.scrollWidth) * trackWidth)
    const thumbLeft = (currentScroll / maxScroll) * (trackWidth - thumbWidth)

    scrollbarThumbWidth.value = thumbWidth
    scrollbarThumbLeft.value = thumbLeft
  }
}

const scrollToPosition = (e) => {
  if (!scrollContainer.value || !scrollbarTrack.value) return

  const trackRect = scrollbarTrack.value.getBoundingClientRect()
  const clickX = e.clientX - trackRect.left
  const trackWidth = scrollbarTrack.value.clientWidth
  const maxScroll = scrollContainer.value.scrollWidth - scrollContainer.value.clientWidth

  const scrollRatio = clickX / trackWidth
  const newScrollLeft = scrollRatio * maxScroll

  scrollContainer.value.scrollLeft = newScrollLeft
}

const startScrollbarDrag = (e) => {
  e.stopPropagation()
  isScrollbarDragging.value = true
  scrollbarStartX.value = e.clientX
  scrollbarThumbStartLeft.value = scrollbarThumbLeft.value

  // 停止自动滚动
  stopAutoScroll()

  // 添加全局鼠标事件监听
  document.addEventListener('mousemove', onScrollbarDrag)
  document.addEventListener('mouseup', stopScrollbarDrag)
}

const onScrollbarDrag = (e) => {
  if (!isScrollbarDragging.value || !scrollContainer.value || !scrollbarTrack.value) return

  const deltaX = e.clientX - scrollbarStartX.value
  const trackWidth = scrollbarTrack.value.clientWidth
  const maxThumbLeft = trackWidth - scrollbarThumbWidth.value

  let newThumbLeft = scrollbarThumbStartLeft.value + deltaX
  newThumbLeft = Math.max(0, Math.min(maxThumbLeft, newThumbLeft))

  scrollbarThumbLeft.value = newThumbLeft

  // 更新容器滚动位置
  const scrollRatio = newThumbLeft / maxThumbLeft
  const maxScroll = scrollContainer.value.scrollWidth - scrollContainer.value.clientWidth
  scrollContainer.value.scrollLeft = scrollRatio * maxScroll
}

const stopScrollbarDrag = () => {
  isScrollbarDragging.value = false

  // 移除全局事件监听
  document.removeEventListener('mousemove', onScrollbarDrag)
  document.removeEventListener('mouseup', stopScrollbarDrag)

  // 重新开始自动滚动
  startAutoScroll()
}

getMesColorDetail()
// getList()
getCardList()
getPrintList()
onMounted(() => {

  // 获取当前环境
  const environment = process.env.NODE_ENV
  if (environment === 'production') {
    baseURL.value = 'http://10.133.100.100:9000/'
  } else {
    baseURL.value = 'http://10.1.7.105/'
  }

  action.value = `${baseURL.value}api/eletile-digital/sys-minio/upload`

  // 启动自动滚动和初始化滚动条
  nextTick(() => {
    startAutoScroll()
    updateScrollProgress()
  })
})

// 监听卡片列表变化，更新滚动条
watch(cardList, () => {
  nextTick(() => {
    updateScrollProgress()
  })
}, { deep: true })

onUnmounted(() => {
  // 清理定时器和事件监听器
  stopAutoScroll()
  stopScrollbarDrag()
})
</script>

<style scoped lang="scss">
@import "./index.scss";

.card-scroll-container {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.card-scroll-wrapper {
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-behavior: smooth;
  cursor: grab;
  padding: 8px 0;

  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */

  &::-webkit-scrollbar {
    display: none; /* Chrome, Safari and Opera */
  }

  /* 防止文本选择 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;

  /* 确保卡片之间有间距 */
  gap: 12px;

  /* 添加一些内边距 */
  padding-left: 8px;
  padding-right: 8px;
}

.card-scroll-wrapper:active {
  cursor: grabbing;
}

.custom-scrollbar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 5px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin: 0 8px 22px 8px;
}

.scrollbar-track {
  position: relative;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  cursor: pointer;
  background-color: rgba(0, 0, 0, 0.05);
}

.scrollbar-thumb {
  position: absolute;
  top: 0;
  height: 100%;
  background-color: rgba(0, 123, 255, 0.8);
  border-radius: 4px;
  cursor: grab;
  transition: background-color 0.2s ease;
  min-width: 20px;
}

.scrollbar-thumb:hover {
  background-color: rgba(0, 123, 255, 1);
}

.scrollbar-thumb:active {
  cursor: grabbing;
  background-color: rgba(0, 123, 255, 1);
}
</style>

